/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.action;

import com.myapp.dao.DaoDocumento;
import com.myapp.dao.DaoFacade;
import com.myapp.dao.DaoUsuario;
import com.myapp.form.IncluirForm;
import com.myapp.model.Documento;
import com.myapp.model.Usuario;
import com.myapp.util.ManipuladoraArquivo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
 *
 * @author elio
 */
public class IncluirDocumentoAction extends org.apache.struts.action.Action {
    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        IncluirForm myform = (IncluirForm) form;
        try {
            //estou utilizando um usuario fixo pois nao tem login
            DaoFacade daoUsuario = DaoUsuario.getInstance();
            Usuario u = (Usuario) daoUsuario.carregarUm(1, Usuario.class);
            
            DaoFacade daoDocumento = DaoDocumento.getInstance();
            //int i = daoDocumento.retornarMaxId(Documento.class);
            
            Documento d = new Documento();
            d.setDescricao(myform.getDescricao());
            d.setTipo(myform.getTipo());
            d.setNumRevisao(myform.getNumRevisao());
            d.setUsuario(u);

             if ((myform.getDescricao() == null) || 
                  myform.getDescricao().equals("") )
             {  
                return mapping.findForward(FAILURE);
             }
                        
            //gravando documento
            daoDocumento.gravar(d);
            int i = daoDocumento.retornarMaxId(Documento.class);
            
            //salvando arquivo
            FormFile myFile = myform.getTheFile();
            byte[] fileData = myFile.getFileData();
            String fileName  = myFile.getFileName();
           
           ManipuladoraArquivo.criarArquivo(String.valueOf(i),fileName, fileData);
            return mapping.findForward(SUCCESS);
        } catch (Exception e) {

            return mapping.findForward(FAILURE);

        }

    }
}
